package com.maniu.serialportnative;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class SerialPort {

    private FileDescriptor mFd;
//     读
    private FileInputStream mFileInputStream;
//    写 while   1/9600
    private FileOutputStream mFileOutputStream;

//    /dev/ttys
    public SerialPort(@NonNull File device) {

        if (!device.canRead() || !device.canWrite()) {

            try {
                /* Missing read/write permission, trying to chmod the file */
                Process su;
//                root权限  ----》  /dev/ttys     root 权限
                su = Runtime.getRuntime().exec( "/system/bin/su");
                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n";
                su.getOutputStream().write(cmd.getBytes());
                if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
                    throw new SecurityException();
                }
                mFd = open(device.getAbsolutePath(), 9600, 8, 1, 1);
            } catch (Exception e) {
                e.printStackTrace();
                throw new SecurityException();
            }

        }

        FileDescriptor fileDescriptor = new FileDescriptor();


        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }

    private native FileDescriptor open(String absolutePath, int baudrate ,int dataBits  , int parity,int stopBits);

    public FileInputStream getFileInputStream() {
        return mFileInputStream;
    }

    public void setmFileInputStream(FileInputStream mFileInputStream) {
        this.mFileInputStream = mFileInputStream;
    }

    public FileOutputStream getFileOutputStream() {
        return mFileOutputStream;
    }

    public void setmFileOutputStream(FileOutputStream mFileOutputStream) {
        this.mFileOutputStream = mFileOutputStream;
    }
}
